import { _decorator, assetManager, EventTarget, Component, Node, Sprite, SpriteFrame, log, ImageAsset, type Texture2D, UIOpacity, tween } from 'cc'
import { fitContainer, Logger } from '../utils'
import { ServiceLocator } from '../utils/locator'
import { FrameEvents, ServiceName } from 'db://assets/enum'
import type { Chapter } from '../store'
const { ccclass, property } = _decorator

@ccclass('BGPFrame')
export class BGPFrame extends Component {

    @property({ type: Node })
    public back: Node = null

    get backImg() {
        return this.back?.getComponent(Sprite)
    }

    @property({ type: Node })
    public container: Node = null

    get containerImg() {
        return this.container?.getComponent(Sprite)
    }

    @property(Node)
    public mask: Node = null

    get maskImg() {
        return this.mask?.getComponent(Sprite)
    }

    get maskOpacity() {
        return this.mask?.getComponent(UIOpacity)
    }

    @property(Node)
    filter: Node = null

    get filterImg() {
        return this.filter?.getComponent(Sprite)
    }


    #log = new Logger('背景帧')
    #services = ServiceLocator


    get chapter(): Chapter {
        return this.#services.get(ServiceName.Chapter)
    }

    get events(): EventTarget {
        return this.#services.get(ServiceName.Event)
    }

    start() {
        this.maskOpacity.opacity = 0

    }


    run(content: LDContent.BGPContent) {
        this.#log.debug('处理背景帧 %o', content)
        tween(this.maskOpacity)
            .to(1, { opacity: 255 }, { easing: 'fade' })
            .call(() => {
                const resource = this.chapter.getResource(content.resourceId)
                assetManager.loadRemote<ImageAsset>(resource.ossUrl, (err, asset) => {
                    this.containerImg.spriteFrame = SpriteFrame.createWithImage(asset)
                    fitContainer(this.container)
                    tween(this.maskOpacity)
                        .to(1, { opacity: 0 }, { easing: 'fade' })
                        .call(() => {
                            this.events.emit(FrameEvents.frameLock, false)
                            this.events.emit(FrameEvents.stepNext)
                        }).start()
                })
            }).start()
    }

}


